import {ProColumns,} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Form, GetRef, Input, InputRef, Popconfirm, Table} from 'antd';
import React, {useContext, useEffect, useRef, useState} from 'react';
import ThrottledButton from "@/components/ThrottledButton";

type FormInstance<T> = GetRef<typeof Form<T>>;

const EditableContext = React.createContext<FormInstance<any> | null>(null);

interface Item {
  key: string;
  paramName: string;
  paramValue: string;
}

interface EditableRowProps {
  index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({index, ...props}) => {
  const [form] = Form.useForm();

  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  dataIndex: keyof Item;
  record: Item;
  handleSave: (record: Item) => void;
}

const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
                                                                              title,
                                                                              editable,
                                                                              children,
                                                                              dataIndex,
                                                                              record,
                                                                              handleSave,
                                                                              ...restProps
                                                                            }) => {
  const [editing, setEditing] = useState(true);
  const inputRef = useRef<InputRef>(null);
  const form = useContext(EditableContext)!;
  useEffect(() => {
    if(record){
      form.setFieldsValue({[dataIndex]: record[dataIndex]});
    }
  }, []);

  // const toggleEdit = () => {
  //   // setEditing(!editing);  // 切换编辑状态
  //   form.setFieldsValue({[dataIndex]: record[dataIndex]}); // 初始化输入框值
  // };

  const save = async () => {
    try {
      const values = await form.validateFields();
      handleSave({...record, ...values});
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };
  let childNode = children
  if (editable) {
    childNode = (
      <Form.Item
        style={{margin: 0}}
        name={dataIndex}
        rules={[{whitespace: true}]}
      >
        <Input
          ref={inputRef}
          onBlur={save}  // 失去焦点时保存
          allowClear={true}
          autoComplete="off"
        />
      </Form.Item>
    );
  }
  return <td {...restProps}>{childNode}</td>;
};

interface DataType {
  key: React.Key;
  paramName: string;
  paramValue: string;
}

export type Props = {
  columns: ProColumns<API.InterfaceInfo>[];
  requestParams: string;
  onCancel: () => void;
  onSubmitData: (values: API.InterfaceInfo) => Promise<void>;
  visible: boolean;
};

const ParamsTable: React.FC<Props> = (props) => {

  const {requestParams, onSubmitData} = props;
  const [count, setCount] = useState(0);
  const [dataSource, setDataSource] = useState<DataType[]>([
    // {
    //   key: 0,
    //   paramName: '',
    //   paramValue: '',
    // }
  ]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleDelete = (key: React.Key) => {
    if (dataSource.length === 1) {
      return
    }
    const newData = dataSource.filter((item) => item.key !== key);
    setDataSource(newData);
  };

  const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
    {
      title: '参数值',
      dataIndex: 'paramName',
      editable: true,
    },
    {
      title: '参数值',
      dataIndex: 'paramValue',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) =>
        dataSource.length >= 1 ? (
          <Popconfirm title="确认删除?" onConfirm={() => handleDelete(record.key)}>
            <a>删除</a>
          </Popconfirm>
        ) : null,
    },
  ];

  const handleAdd = (item) => {
    const newData: DataType = {
      key: count,
      paramName: (typeof item === 'string') ? item : "",
      paramValue: "",
    };
    setDataSource([...dataSource, newData]);
    setCount(count + 1)
  };

  const handleSave = (row: DataType) => {
    // 创建 dataSource 的副本
    const newData = [...dataSource];
    // 找到当前行的索引
    const index = newData.findIndex((item) => row.key === item.key);
    // 如果找到该行
    if (index > -1) {
      const item = newData[index];  // 获取当前行的原始数据
      // 更新该行的数据
      newData.splice(index, 1, {...item, ...row});  // 只更新 row 中有变化的字段
      console.log('保存后的数据：', row, newData, index, item);
      setDataSource(newData);  // 更新表格数据
    }
    // else {
    //   // 如果未找到，可能是新增的数据，直接追加到 dataSource
    //   newData.push(row);
    //   setDataSource(newData);
    // }
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  useEffect(() => {
    if (requestParams) {
      const requestParamsJson = JSON.parse(requestParams)
      Object.keys(requestParamsJson).forEach((item, index) => {
        handleAdd(item)
        handleSave({
          key: index,
          paramName: item,
          paramValue: '',
        })
        setCount(count + 1)
      })
    }
  }, [requestParams]);



  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  const onSubmit = async () => {
    const result = dataSource.reduce((acc, item) => {
      if (selectedRowKeys.includes(item.key)) {
        if (item.paramName) {
          acc[item.paramName] = item.paramValue;
        }
        return acc;
      }
      return acc
    }, {});
    // 将转换后的列表转换为 JSON 字符串
    const jsonString = JSON.stringify(result, null, 2);  // 格式化为漂亮的 JSON 字符串
    console.log(result, dataSource)
    await onSubmitData?.({
      userRequestParams: jsonString
    })
  }

  return (
    <div>
      <Table<DataType>
        components={components}
        rowSelection={rowSelection}
        rowClassName={() => 'editable-row'}
        bordered
        dataSource={dataSource}
        columns={columns as ColumnTypes || []}
        pagination={false}
      />
      <div style={{marginTop: 20}}>
        <Button onClick={handleAdd} type="primary" style={{marginBottom: 7}}>
          添加参数
        </Button>
        {/*<Button onClick={onSubmit} type="primary" style={{marginLeft: 7}}>*/}
        {/*  调用*/}
        {/*</Button>*/}
        <ThrottledButton submit={onSubmit}  mLeft={7} title={"调用"}></ThrottledButton>
      </div>
    </div>
  );
};
export default ParamsTable;
